<?php

namespace Managers;

class Resources extends BaseManager {

    protected $__table = '\Catalog\Resources';

    public function getList() {
        $res = $this->_em->createQueryBuilder()
                ->select('r', 'p')
                ->from($this->__table, 'r')
                ->join('r.privileges', 'p')
                ->getQuery()
                ->getArrayResult();
        return $res;
    }

    public function getTreeList($parent = null) {

        $cacheName = 'resources_tree_' . $parent;
        $res = $this->_getCacheManager()->load($cacheName);

        if (!$res) {

            $qb = $this->_em->createQueryBuilder()
                    ->select('r')
                    ->from($this->__table, 'r');
            if ($parent) {
                $qb = $qb->where('r.parent = :parent')
                        ->setParameter('parent', $parent);
            } else {
                $qb = $qb->where('r.parent is null');
            }

            $res = $qb->getQuery()
                    ->getArrayResult();

            foreach ($res as $i => $item) {
                $res[$i]['children'] = $this->getTreeList($item['id']);
            }

            $this->_getCacheManager()->save($res, $cacheName);
        }

        return $res;
    }

}
